package com.itheima.pinda.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.pinda.DTO.user.CourierScopeDto;
import com.itheima.pinda.common.CustomIdGenerator;
import com.itheima.pinda.entity.PdCourierScope;
import com.itheima.pinda.mapper.PdCourierScopMapper;
import com.itheima.pinda.service.PdCourierScopeService;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class PdCourierScopeServiceImpl implements PdCourierScopeService {
    @Autowired
    private CustomIdGenerator idGenerator;
    @Autowired
    private PdCourierScopMapper courierScopMapper;


    @Override
    @Transactional
    public void batchSaveCourierScope(List<CourierScopeDto> dtoList) {
        dtoList.forEach(courierScopeDto -> {
            PdCourierScope courierScope = new PdCourierScope();
            BeanUtils.copyProperties(courierScopeDto,courierScope);
            courierScope.setId(idGenerator.nextId(courierScope) + "");
            courierScopMapper.insert(courierScope);
        });
    }

    @Override
    public void deleteCourierScope(CourierScopeDto dto) {
        if (StringUtils.isEmpty(dto.getAreaId()) && StringUtils.isEmpty(dto.getUserId())) {
            throw new RuntimeException("请传入删除条件！");
        }
        courierScopMapper.delete(new LambdaQueryWrapper<PdCourierScope>()
                .eq(!StringUtils.isEmpty(dto.getAreaId()),PdCourierScope::getAreaId,dto.getAreaId())
                .eq(!StringUtils.isEmpty(dto.getUserId()),PdCourierScope::getUserId,dto.getUserId()));
    }

    @Override
    public List<CourierScopeDto> findAllCourierScope(String areaId, String userId) {

        List<PdCourierScope> courierScopes = courierScopMapper.selectList(new LambdaQueryWrapper<PdCourierScope>()
                .eq(!StringUtils.isEmpty(areaId), PdCourierScope::getAreaId, areaId)
                .eq(!StringUtils.isEmpty(userId), PdCourierScope::getUserId, userId));

        List<CourierScopeDto> collect = courierScopes.stream().map((pdCourierScope -> {
            CourierScopeDto courierScopeDto = new CourierScopeDto();
            BeanUtils.copyProperties(courierScopes, courierScopeDto);
            return courierScopeDto;
        })).collect(Collectors.toList());

        return collect;
    }
}
